package com.atguigu.gmall.common.config;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.config.constant.MqCons;
import com.atguigu.gmall.common.config.entity.GmallCorrelationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @Description 消息发送确认
 * <p>
 * ConfirmCallback  只确认消息是否正确到达 Exchange 中
 * ReturnCallback   消息没有正确到达队列时触发回调，如果正确到达队列不执行
 * <p>
 * 1. 如果消息没有到exchange,则confirm回调,ack=false
 * 2. 如果消息到达exchange,则confirm回调,ack=true
 * 3. exchange到queue成功,则不回调return
 * 4. exchange到queue失败,则回调return
 */
@Component
@Slf4j
public class MQProducerAckConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;


    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);            //指定 ConfirmCallback
        rabbitTemplate.setReturnCallback(this);             //指定 ReturnCallback
    }

    //确认 消息是否发送到交换机
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("消息发送成功：" + JSON.toJSONString(correlationData));
        } else {
            log.info("消息发送失败：" + cause + " 数据：" + JSON.toJSONString(correlationData));
            //重新发送
            GmallCorrelationData gmallCorrelationData = (GmallCorrelationData) correlationData;
            this.addRetry(gmallCorrelationData);
        }
    }

    //重新发送
    private void addRetry(GmallCorrelationData gmallCorrelationData) {
        try {
            int retryCount = gmallCorrelationData.getRetryCount();
            if (retryCount < MqCons.RETRY_COUNT) {
                //更新重发次数
                gmallCorrelationData.setRetryCount(++retryCount);
                //更新重发次数
                redisTemplate.opsForValue().set(gmallCorrelationData.getId(),
                        JSON.toJSONString(gmallCorrelationData),
                        MqCons.OBJECT_TIME, TimeUnit.MINUTES);
                log.info("5秒之后重新发送:" + JSON.toJSONString(gmallCorrelationData));
                //休息5分钟
                Thread.sleep(5000);
                if(gmallCorrelationData.isDelay()){
                    rabbitTemplate.convertAndSend(gmallCorrelationData.getExchange(),
                            gmallCorrelationData.getRoutingKey()
                            , gmallCorrelationData.getMessage(),m -> {
                                m.getMessageProperties().setDelay(gmallCorrelationData.getDelayTime());
                                return m;
                            },
                            gmallCorrelationData);
                }else{
                    rabbitTemplate.convertAndSend(gmallCorrelationData.getExchange(),
                            gmallCorrelationData.getRoutingKey()
                            , gmallCorrelationData.getMessage(),
                            gmallCorrelationData);
                }
            } else {
                //重发次数用尽
                log.info("重发次数用尽:" + JSON.toJSONString(gmallCorrelationData));
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    //确认消息送达队列
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        // 反序列化对象输出
//        System.out.println("消息主体: " + new String(message.getBody()));
//        System.out.println("应答码: " + replyCode);
//        System.out.println("描述：" + replyText);
//        System.out.println("消息使用的交换器 exchange : " + exchange);
//        System.out.println("消息使用的路由键 routing : " + routingKey);
        String id = (String) message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");
        String correlationData = (String) redisTemplate.opsForValue().get(id);
        if(StringUtils.isEmpty(correlationData)){
            return;
        }
        GmallCorrelationData gmallCorrelationData = JSON.parseObject(correlationData, GmallCorrelationData.class);
        if(gmallCorrelationData.isDelay()){
            log.info("是延迟消息造成的队列应答：无需重新发送");
            return;
        }
        this.addRetry(gmallCorrelationData);
    }


}